<template>
  <div id="labCompanyFeeitemDiv">
    <Breadcrumb content="预制样本条码" />
    <div class="bodyContent">
      <el-tabs v-model="activeName" type="card" @tab-click="getData">
        <el-tab-pane label="预制条码" name="precutBarCode" >
          <vxe-toolbar perfect>
            <template #buttons>
              <el-form :model="searchForm" :rules="reqNoFormRule" class="form-input-m" label-width="80px" :inline="true">
                <el-form-item prop="reqCompanyName" label="预制机构">
                  <VxePulldownSelection  :isChild="false" ref="pdownCompany" :url="'/lab/inspectCompany/findInspectCompanyList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'companyName', title: '名称' },
                          { field: 'companyCode', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'reqCompanyName', rowKey: 'companyName' },
                          { aimKey: 'reqCompany', rowKey: 'companyCode' },
                          { aimKey: 'companyRules', rowKey: 'companyRules' }

                        ]" :displayTexts="['reqCompanyName']" :displayTextObj="searchForm.reqCompanyName ? searchForm.reqCompanyName : ''" :dataObj="null" />
                </el-form-item>
                <el-form-item prop="amount" label="预制数量">
                  <vxe-input  type="number" :min="1" v-model="searchForm.amount" clearable ></vxe-input>
                </el-form-item>
                <el-form-item prop="reqTime" label="预制时间">
                  <vxe-input  type="datetime" v-model="searchForm.reqTime" clearable ></vxe-input>
                </el-form-item>
                <el-form-item>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="预制条码" @click="makeReqNo"></vxe-button>
                  <vxe-button type="text" class="button-green" icon="vxe-icon-print" content="打印条码" @click="printReqNo(null)"></vxe-button>
                </el-form-item>
              </el-form>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="reqDetailTableRef" :data="reqNoList" :loading="reqNoLoading"   align="center" height="800" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" width="24" fixed="left"></vxe-column>
              <vxe-column field="reqNo" title="预制条码号" width="300"></vxe-column>
              <vxe-column field="companyName" title="机构名称" width="800"></vxe-column>
              <vxe-column field="reqTime" title="预制时间" width="180"></vxe-column>
              <vxe-column title="操作" fixed="right"  align="center">
                <template #default="{ row }">
                  <vxe-button type="text" status="danger" icon="vxe-icon-delete"  content="删除" @click="deleteReqNo({ row })"></vxe-button>
                </template>
              </vxe-column>

            </vxe-table>
          </div>

        </el-tab-pane>
        <el-tab-pane label="预制记录" name="precutLog" style="height: 100%">
          <vxe-toolbar perfect>
            <template #buttons>
              <el-form :model="searchLogForm" :rules="reqNoFormRule" class="form-input-m" label-width="80px" :inline="true">
                <el-form-item prop="reqCompanyName" label="预制机构">
                  <VxePulldownSelection  :isChild="false" ref="pdownCompany" :url="'/lab/inspectCompany/findInspectCompanyList'" @confirmClick="SelectRowClick" :tableColumn="[
                          { type: 'seq', title: '#', width: '30px' },
                          { field: 'companyName', title: '名称' },
                          { field: 'companyCode', title: '编码' }
                        ]" :aimKeys="[
                          { aimKey: 'reqCompanyName', rowKey: 'companyName' },
                          { aimKey: 'reqCompany', rowKey: 'companyCode' },
                          { aimKey: 'companyRules', rowKey: 'companyRules' }
                        ]" :displayTexts="['reqCompanyName']" :displayTextObj="searchLogForm.reqCompanyName ? searchLogForm.reqCompanyName : ''" :dataObj="null" />
                </el-form-item>
                <el-form-item prop="reqNo" label="预制条码号">
                  <vxe-input  type="text"  v-model="searchLogForm.reqNo" clearable @blur="queryReqNo"></vxe-input>
                </el-form-item>
                <el-form-item prop="reqNo" label="条码号范围">
                  <vxe-input  class="enterNextInputFlag" type="text" v-model="searchLogForm.reqNoStart" placeholder="条码号[起]" clearable class-name="width-100-percentage" ></vxe-input>
                  <span>-</span>
                  <vxe-input  class="enterNextInputFlag" type="text" v-model="searchLogForm.reqNoEnd" placeholder="条码号[止]" clearable class-name="width-100-percentage" ></vxe-input>
                </el-form-item>
                <el-form-item label="是否使用">
                  <el-select v-model="searchLogForm.useState" placeholder="请选择" size="small" clearable style="width:160px" teleported @blur="queryReqNo">
                    <el-option label="全部" value="null" />
                    <el-option label="是"  value="1" />
                    <el-option label="否"  value="0" />
                  </el-select>
                </el-form-item>
                <el-form-item label="预制日期" clearable>
                  <el-date-picker v-model="searchLogForm.startTime" type="date" placeholder="起始日期" clearable/>
                  <div>-</div>
                  <el-date-picker v-model="searchLogForm.endTime" type="date" placeholder="截至日期" clearable />
                </el-form-item>
                <el-form-item>
                  <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="查询" @click="queryReqNo"></vxe-button>
                  <vxe-button type="text" class="button-green" icon="vxe-icon-print" content="批量打印" @click="batchPrint"></vxe-button>
                </el-form-item>
              </el-form>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="reqDetailTableRef" :data="reqNoLogList" :loading="queryLoading"   align="center" height="800" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" width="24" fixed="left"></vxe-column>
              <vxe-column type="checkbox" width="20"></vxe-column>
              <vxe-column field="reqNo" title="条码号" width="300"></vxe-column>
              <vxe-column field="companyName" title="机构名称" width="800"></vxe-column>
              <vxe-column field="reqTime" title="预制时间" ></vxe-column>
              <vxe-column field="useState" title="条码状态">
                <template #default="{ row }">
                  <span >{{ row.useState === 1 ? '是' : '否' }}</span>
                </template>
              </vxe-column>
              <vxe-column field="useTime" title="使用时间" ></vxe-column>
              <vxe-column title="重打条码" fixed="right"  align="center">
                <template #default="{ row }">
                  <vxe-button type="text" status="danger" icon="vxe-icon-print"  content="" @click="printReqNo({ row })"></vxe-button>
                </template>
              </vxe-column>

            </vxe-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
  <!-- 静默打印 -->
  <QuietPrint ref="quietPrintRef" :printParams="printParamsObj" />
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import VxePulldownSelection from '@/components/VxePulldownSelection.vue';
let { proxy }: any = getCurrentInstance();
import {AppStore} from "@/stores/store";
import {VxeMessage, VxeNotifyType} from "@/utils/CommonMessage";
import {formatDateTime} from "@/utils/common";
import {isEmpty} from "lodash";
import QuietPrint from '@/components/QuietPrint.vue';


let activeName = ref('precutBarCode');
let store = AppStore();
const reqNoList = reactive([]);
const reqNoLogList = reactive([]);
let reqNoLoading = ref(false);
let queryLoading = ref(false);
let printParamsObj = ref(null); //打印参数
let reportId = ref('');


let reqNoFormRule: any = {
  reqCompanyName: [
    {
      required: true,
      message: '请选择预制机构',
      trigger: 'blur'
    }
  ],
  amount: [
    {
      required: true,
      message: '请输入预制数量',
      trigger: 'blur'
    }
  ]
};

const searchForm = reactive({
  reqCompany:'' ,
  reqCompanyName:'' ,
  companyRules:'' ,
  amount: 1,
  reqTime: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),
  orgId: store.userInfo.orgId
});
const searchLogForm = reactive({
  reqCompany:'' ,
  reqCompanyName:'' ,
  reqNo:'' ,
  reqNoStart:'' ,
  reqNoEnd:'' ,
  useState: 'null' ,
  startTime:formatDateTime(new Date(), 'yyyy-MM-dd'),
  endTime:formatDateTime(new Date(), 'yyyy-MM-dd'),
  orgId: store.userInfo.orgId
});

// 页面加载时更新列表(左侧)
onMounted(() => {
  findInspectCompany(); //批量获取字典
  getReportIdByUrl();
});

function getReportIdByUrl() {
  //先根据路由的URL获取对应的报表信息
  const url = '/api/pubReport/getReportIdByUrl';
  proxy.$http
      .get(url, { params: { url: '/' + proxy.$route.name } })
      .then((res: any) => {
        reportId=res.data;
      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');
      });
}

function findInspectCompany(){
  const url = '/lab/inspectCompany/findInspectCompanyList';
  proxy.$http
      //注意此处的数据条数
      .get(url)
      .then((res: any) => {
        if (res && res.data && res.data.length >= 0) {
          searchForm.reqCompany=res.data[0].companyCode;
          searchLogForm.reqCompany=res.data[0].companyCode;
          searchForm.reqCompanyName=res.data[0].companyName;
          searchLogForm.reqCompanyName=res.data[0].companyName;
          searchForm.companyRules=res.data[0].companyRules;
        }
      })
      .catch((err: any) => {
      });
}

/**下拉选中行事件 */
function SelectRowClick(e) {
  searchForm.companyRules='';
  e.aimKeys.forEach((r) => {
    searchForm[r.aimKey] = e.row[r.rowKey];
    searchLogForm[r.aimKey] = e.row[r.rowKey];
  });
  proxy.$nextTick(() => {
    queryReqNo();
  })
}

function getData(tab) {
  if (tab.paneName == 'precutBarCode') {
    //getWklt();
  } else {
    queryReqNo();
  }
}

//预制条码
function makeReqNo() {
  if (searchForm.amount <= 0) {
    VxeMessage('预制数量大于0', VxeNotifyType.error);
    return;
  }
  if (isEmpty(searchForm.reqCompanyName)) {
    VxeMessage('请选择预制机构', VxeNotifyType.error);
    return;
  }
  if (isEmpty(searchForm.companyRules)) {
    VxeMessage('请设置该机构条码预制规则', VxeNotifyType.error);
    return;
  }
  proxy
      .$confirm('确定预制此批次条码？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        reqNoLoading.value = true;
        reqNoList.length = 0; //放入数据前清空数据
        const url = '/lab/inspectCompanyReqno/makeReqNoList';
        const data = {
          companyCode: searchForm.reqCompany,
          companyName: searchForm.reqCompanyName,
          companyRules: searchForm.companyRules,
          amount: searchForm.amount,
          reqTime: searchForm.reqTime
        }
        proxy.$http
            //注意此处的数据条数
            .post(url, data)
            .then((res: any) => {
              reqNoList.push(...res.data);
              reqNoLoading.value = false;
            })
            .catch((err: any) => {
              reqNoLoading.value = false;
            });
      });

}

//打印条码
function printReqNo(row :any){
  let ids ='';
  if (isEmpty(row)){
    if (reqNoList.length <=0 ){
      VxeMessage('没有要打印的条码', VxeNotifyType.info);
    }
    const commaSeparatedIds = reqNoList.map((row) => row.id);
    ids = commaSeparatedIds.join(',');
  }else {
    ids=row.row.id;
  }
  // 调用报表,发送打印任务
  printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'ids', Value: ids }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };

}
//批次打印条码
function batchPrint(){
  const $xTable = proxy.$refs.reqDetailTableRef as any;
  const selectRows = $xTable.getCheckboxRecords();
  if (!(selectRows && selectRows.length > 0 && selectRows[0])) {
    VxeMessage('请先选中要打印的条码', VxeNotifyType.info);
  }else {
    const commaSeparatedIds = selectRows.map((row) => row.id);
    let ids = commaSeparatedIds.join(',');

    // 调用报表,发送打印任务
    printParamsObj.value = [{ ReportName: reportId, ReportParameters: [{ Name: 'ids', Value: ids }], PdfPrinterSetting: { PdfPrinterCopies: 1 } }]; // { id: new Date().valueOf(), params: ['123', '345', '567'] };

  }

}

//删除预制条码
function deleteReqNo({row}) {

  proxy
      .$confirm('确定删除'+row.reqNo+'预制条码？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        //后台删除数据
        const url = '/lab/inspectCompanyReqno/deleteReqNo';
        proxy.$http
            .post(url, row)
            .then((res: any) => {
              if (res.status.code === 1) {
               //集合根据id 删除
                const index = reqNoList.findIndex(item => item.id === res.data);
                if (index !== -1) {
                  reqNoList.splice(index, 1);
                }
                VxeMessage('删除成功!', VxeNotifyType.success);
              }

            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
      });

}
//查询预制记录
function queryReqNo(){
  if (isEmpty(searchLogForm.reqCompanyName)) {
    VxeMessage('请选择预制机构', VxeNotifyType.error);
    return;
  }
  queryLoading.value = true;
  reqNoLogList.length = 0; //放入数据前清空数据
  const url = '/lab/inspectCompanyReqno/getReqNoList';
  const data = {
    companyCode: searchLogForm.reqCompany,
    companyName: searchLogForm.reqCompanyName,
    reqNo: searchLogForm.reqNo,
    reqNoStart: searchLogForm.reqNoStart,
    reqNoEnd: searchLogForm.reqNoEnd,
    useState: (searchLogForm.useState === 'null' ? null : searchLogForm.useState),
    startTime: (isEmpty(searchLogForm.startTime) ? null : searchLogForm.startTime+' 00:00:00'),
    endTime: (isEmpty(searchLogForm.endTime) ? null : searchLogForm.endTime+' 23:59:59')
  }
  proxy.$http
      //注意此处的数据条数
      .post(url, data)
      .then((res: any) => {
        reqNoLogList.length = 0; //放入数据前清空数据
        reqNoLogList.push(...res.data);
        queryLoading.value = false;
      })
      .catch((err: any) => {
        queryLoading.value = false;
      });

}


</script>

<style lang="scss" scoped>
#labCompanyFeeitemDiv {
  height: 100%;

  .bodyContent {
    height: calc(100% - 160px);
    background-color: $base-white;

    :deep(.el-tabs) {
      height: 100%;
      .el-tabs__content {
        height: calc(100% - 70px);
        .el-tab-pane {
          height: 100%;
        }
        .tableBox{
          height: 100%;
        }
      }
    }

    // 附加按钮间距
    .button-blue,
    .button-green{
      margin: 5px 0 5px 5px;
    }
  }
}
</style>